package com.villaday.idf.fragment;


import android.content.Intent;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.m7.imkfsdk.KfStartHelper;

import com.villaday.idf.R;
import com.villaday.idf.activity.MessageListType0Activity;
import com.villaday.idf.adapter.MessageTypeAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.AllReadEntity;
import com.villaday.idf.model.LoginEntity;
import com.villaday.idf.model.MessageTypesEntity;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;

import static android.app.Activity.RESULT_OK;

/**
 * 消息中心
 */
public class MessageFragment extends BaseFragment implements OkHttpUtil.OnDataListener, View.OnClickListener, OnAdapterCallbackListener, AbsRecyclerViewAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.ll_lxKf)
    LinearLayout llLxKf;
    @BindView(R.id.rv)
    RecyclerView rv;

    @BindView(R.id.srl)
    SwipeRefreshLayout srl;


    private LoadingDialog loadingDialog;
    private MessageTypeAdapter messageTypeAdapter;
    private Gson gson = new GsonBuilder().create();
    private MessageTypesEntity messageTypesEntity;
    private Jump2Page jump2Page;
    private String roleType;
    private StatusLayoutManager statusLayoutManager;


    public MessageFragment() {
        // Required empty public constructor
    }


    public static MessageFragment instance() {
        MessageFragment messageFragment = new MessageFragment();
        return messageFragment;
    }

    @Override
    protected int getViewResId() {
        return R.layout.fragment_message2;
    }

    @Override
    protected void init(View v) {

        statusLayoutManager = setupDefaultStatusLayoutManager(srl, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");

                loadData();
                 }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });

        RefreshtokenEntity.BodyBean roleInfo =
                SharedPreferencesUtil.getRoleInfo(getContext());
        roleType = roleInfo.getMember().getType();


        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getActivity().getFragmentManager(), "loading");
        srl.setOnRefreshListener(this);
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        messageTypeAdapter = new MessageTypeAdapter(getContext(), this, this);
        rv.setAdapter(messageTypeAdapter);
        messageTypeAdapter.setOnItemClickListener(this);
        final KfStartHelper helper = new KfStartHelper(getActivity());
        LoginEntity userInfo = SharedPreferencesUtil.getUserInfo(getContext());
        /*IMChatManager.getInstance().init(AppContext.getInstance(),
                "com.villaday.idf.7mss",
                "c57dcce0-d1b2-11e8-ab14-fd304d737e13",
                userInfo.getBody().getMember().getId(),
                userInfo.getBody().getMember().getNickName());

        IMChatManager.getInstance().setOnInitListener(new InitListener() {
            @Override
            public void oninitSuccess() {
                LogUtil.d("MobileApplication", "sdk初始化成功");

                int unReadCount = IMChatManager.getInstance().getMsgUnReadCount();

                ToastUtil.initToast(getContext(),unReadCount+"");
            }
            @Override
            public void onInitFailed() {
                LogUtil.d("MobileApplication", "sdk初始化失败");
            }
        });
*/


    }

    @Override
    protected void loadData() {
        OkHttpUtil.getJSON(getContext(), Constant.URL.member_message_types, this);
    }

    @OnClick(R.id.ll_lxKf)
    public void onViewClicked() {

        final KfStartHelper helper = new KfStartHelper(getActivity());
        LoginEntity userInfo = SharedPreferencesUtil.getUserInfo(getContext());

        helper.initSdkChat("com.villaday.idf.7mss", userInfo.getBody().getMember().getNickName(), userInfo.getBody().getMember().getId());

        /*//⾸先判断是否在此之前初始化过sdk,获取消息参数需userid等参数
        if (MoorUtils.isInitForUnread(getContext())) {
            IMChatManager.getInstance().getMsgUnReadCountFromService(
                    new IMChatManager.HttpUnReadListen() {
                        @Override
                        public void getUnRead(int acount) {
                            Toast.makeText(getContext(), "未读消息数为：" + acount,
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
        } else {
            //未初始化，消息当然为 ：0
            Toast.makeText(getContext(), "还没初始化", Toast.LENGTH_SHORT).show();
        }*/

    }

    @Override
    public void onResponse(String url, String json) {
        if (statusLayoutManager != null) {
            statusLayoutManager.showSuccessLayout();
        }
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.member_message_types.equals(url)) {
                LogeUtil.e("member_message_types", json);
                messageTypesEntity = gson.fromJson(json, MessageTypesEntity.class);
                if (messageTypesEntity.getBody() != null && messageTypesEntity.getBody().size() != 0) {
                    rv.setVisibility(View.VISIBLE);
                    messageTypeAdapter.setData(messageTypesEntity.getBody());
                } else {
                    rv.setVisibility(View.GONE);
                }
            } else if (Constant.URL.member_message_all_read.equals(url)) {
                LogeUtil.e("member_message_all_read", json);
                AllReadEntity allReadEntity = gson.fromJson(json, AllReadEntity.class);
                if (allReadEntity.getBody().getStatus() == 1) {
                    ToastUtil.initToast(getContext(), "操作成功");
                    loadData();
                } else {
                    ToastUtil.initToast(getContext(), "操作失败");

                }
            }
        }
        dismissLoading();
    }

    @Override
    public void onFailure(String url, String error) {
        if (Constant.URL.member_message_types.equals(url)) {
            if (statusLayoutManager != null) {
                statusLayoutManager.showErrorLayout();
            }
            ToastUtil.initToast(getContext(),"网络错误");
        }
        dismissLoading();
    }

    private void dismissLoading() {
        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }

        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onCallback() {

    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent = new Intent(getContext(), MessageListType0Activity.class);
        intent.putExtra("messageType", messageTypesEntity.getBody().get(position).getMessageType());
        startActivityForResult(intent, 123);

    }


    @OnClick({R.id.tv_allRead,R.id.ib_fn_back})
    public void onViewClicked1(View view) {
        switch (view.getId()){
            case R.id.tv_allRead:
                if (messageTypesEntity != null && messageTypesEntity.getBody() != null && messageTypesEntity.getBody().size() != 0)
                    for (int i = 0; i < messageTypesEntity.getBody().size(); i++) {
                        if (messageTypesEntity.getBody().get(i).getBadge() != 0) {
                            loadingDialog = LoadingDialog.newInstance("操作中");
                            loadingDialog.show(getActivity().getFragmentManager(), "loading");
                            OkHttpUtil.getJSON(getContext(), Constant.URL.member_message_all_read, this);
                            return;
                        }

                    }
                break;
            case R.id.ib_fn_back:
                getActivity().setResult(RESULT_OK);
                getActivity().finish();
                break;
        }


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 123) {
                loadData();
            }

//            if ("page/home".equals(data.getStringExtra("type"))) {
//                jump2Page.jump2Page(0, 0);
//
//            } else if ("page/home/material".equals(data.getStringExtra("type"))) {
//                jump2Page.jump2Page(0, 0);
//
//            } else if ("page/home/presell".equals(data.getStringExtra("type"))) {
//                if ("0".equals(roleType)) {
//                    jump2Page.jump2Page(0, 0);
//
//                } else {
//                    jump2Page.jump2Page(0, 1);
//
//                }
//
//            } else if ("page/home/topic".equals(data.getStringExtra("type"))) {
//                if ("0".equals(roleType)) {
//                    jump2Page.jump2Page(0, 1);
//
//                } else {
//                    jump2Page.jump2Page(0, 2);
//
//                }
//
//            } else if ("page/village".equals(data.getStringExtra("type"))) {
//
//                jump2Page.jump2Page(1, 0);
//            } else if ("page/vip".equals(data.getStringExtra("type"))) {
//
//                jump2Page.jump2Page(2, 0);
//            } else if ("page/member".equals(data.getStringExtra("type"))) {
//
//                jump2Page.jump2Page(4, 0);
//            }


        }
    }

    @Override
    public void onRefresh() {
        loadData();
    }

    public void setjump2Page(Jump2Page jump2Page) {

        this.jump2Page = jump2Page;
    }

    public interface Jump2Page {

        void jump2Page(int page, int innerPage);
    }
}
